package com.lostandfound.filter;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

/**
 * Application Lifecycle Listener implementation class OnLineUsers
 *
 */
@WebListener
public class OnLineUsers implements HttpSessionBindingListener {
	
	private Map<String, HttpSession> sessions = new HashMap<String, HttpSession>();  
	  
    private static OnLineUsers onlineUsers = new OnLineUsers();  
  
    public static OnLineUsers getInstance() {  
        return onlineUsers;  
    }  
      
    /** 
     * @return 
     */  
    @SuppressWarnings("rawtypes")
	public Collection getSessions() {  
        return sessions.values();  
    }  
  
    public void addSession(HttpSession session) {  
    	sessions.put(session.getId(), session);  
    }  
  
    public void removeSession(String sessionId) {  
    	sessions.remove(sessionId);  
    }

    /**
     * Default constructor. 
     */
    public OnLineUsers() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
     */
    public void valueBound(HttpSessionBindingEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	/**
	 * 当Session超时，或本实例被从session中移除的时候被调用，这种情况一般 发生在注销方法的处理过程中 
     * @see HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
     */
    public void valueUnbound(HttpSessionBindingEvent arg0)  { 
    	try {  
            HttpSession session = arg0.getSession();  
            System.out.println("删除用户回话:"+session.getId());  
            this.removeSession(session.getId());  
        } catch (RuntimeException e) {  
             e.printStackTrace();  
//          throw e;  
        }
    }
	
}
